package com.huluobo.a2110mvpimdemo.chat;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.huluobo.a2110mvpimdemo.R;
import com.huluobo.a2110mvpimdemo.adapter.MessageAdapter;
import com.huluobo.a2110mvpimdemo.base.BaseActivity;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;

import java.util.List;

public class MyChatActivity extends BaseActivity<ChatContract.View, ChatPresenter> implements ChatContract.View {

    private ImageView back;
    private TextView title;
    private String username;

    private EditText chatEdit;
    private ImageView sendBtn;

    private RecyclerView recyclerView;
    private MessageAdapter messageAdapter;

    private EMMessageListener messageListener = new EMMessageListener() {
        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            //每当接收到消息的时候,往presenter中的数据源添加新消息
            presenter.addMessage(username, messages);
            runOnUiThread(() -> {
                messageAdapter.notifyDataSetChanged();
                scrollToBottom();
            });
        }
    };

    @Override
    protected void initData() {
        presenter = new ChatPresenter();
        recyclerView = findViewById(R.id.chat_rv);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        messageAdapter = new MessageAdapter(presenter.messages);
        recyclerView.setAdapter(messageAdapter);

        EMClient.getInstance().chatManager().addMessageListener(messageListener);
        presenter.loadMessage(username);//进入页面就需要加载一次历史消息

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                //当recyclerView处于一个空闲的状态时
                //SCROLL_STATE_IDLE 滑动状态 空闲
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    //通过layoutManager获取到第一个显示的item的position
                    LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (layoutManager != null) {
                        if (layoutManager.findFirstVisibleItemPosition() == 0) {
                            //如果item的position等于0,证明已经滑动到头,可以进行加载更多数据
                            presenter.loadMoreMessage(username);
                        }
                    }
                }
            }
        });
    }

    @Override
    protected void initView() {
        back = findViewById(R.id.header_back);
        title = findViewById(R.id.header_title);

        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(v -> {
            finish();
        });

        username = getIntent().getExtras().getString("conversationId");
        title.setText(username);

        chatEdit = findViewById(R.id.chat_edit);
        sendBtn = findViewById(R.id.chat_send);

        chatEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    sendBtn.setEnabled(true);
                } else {
                    sendBtn.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        sendBtn.setOnClickListener(v -> {
            presenter.sendMessage(chatEdit.getText().toString(), username);
        });


    }

    @Override
    protected int bindLayoutId() {
        return R.layout.activity_my_chat;
    }

    @Override
    public void onStartSendMessage() {

    }

    @Override
    public void onSendMessageSuccess() {
        runOnUiThread(() -> {
            chatEdit.setText("");
            messageAdapter.notifyDataSetChanged();
            scrollToBottom();
        });
    }

    private void scrollToBottom() {
        recyclerView.smoothScrollToPosition(presenter.messages.size() - 1);//平滑移动到对应的位置
    }

    @Override
    public void onSendMessageFailed(String error) {

    }

    @Override
    public void onMessageLoaded() {
        runOnUiThread(() -> {
            messageAdapter.notifyDataSetChanged();
            scrollToBottom();
        });
    }

    @Override
    public void onMoreMessageLoaded(int size) {
        runOnUiThread(() -> {
            messageAdapter.notifyDataSetChanged();
            recyclerView.scrollToPosition(size);
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //当页面销毁时,移除掉消息监听器
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
    }
}